package com.example.rwq_test.designParttern.multiThread.TwoPhaseTermination;

import java.util.concurrent.TimeUnit;

/**
 *
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2022/11/19
 */
public class CountUpThread extends Thread {
    /**
     * 计数器
     */
    private long counter = 0;
    /**
     * 发出终止请求后变成true
     */
    private volatile boolean shutdownRequested = false;
    /**
     * 终止请求
     */
    public void shutdownRequest() {
        shutdownRequested = true;
        interrupt();
    }

    /**
     * 检查是否发出了终止请求
     */
    public boolean isShutdownRequested() {
        return shutdownRequested;
    }

    /**
     * 线程体
     */
    public final void run() {
        try {
            while (!isShutdownRequested()) {
                doWork();
            }
        } catch (InterruptedException e) {

        } finally {
            doShutdown();
        }
    }

    /**
     * 操作
     */
    private void doWork() throws InterruptedException {
        counter++;
        System.out.println("doWork: counter = " + counter);
        TimeUnit.MILLISECONDS.sleep(500);
    }

    /**
     * 终止处理
     */
    private void doShutdown() {
        System.out.println("doShutdown: counter = " + counter);
    }
}
